package top.pengdong.pictureShare.tweet.config;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.dfa.FoundWord;
import cn.hutool.dfa.SensitiveUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import java.io.File;
import java.net.URL;
import java.util.List;

/**
 * @Author: StephenZhang
 * @date: 2021-06-30 17:37
 */
@Component
public class SensitiveWordConfig implements InitializingBean {

    private static final Logger logger = LoggerFactory.getLogger(SensitiveWordConfig.class);

	public static String text;

	/**
	 * 初始化敏感词汇
	 */
    @Override
    public void afterPropertiesSet() {
        URL path = ResourceUtil.getResource("txtTemplate/synthesize.txt");
        File file = FileUtil.file(path);
        FileReader reader = new FileReader(file);
		text = reader.readString();
        SensitiveUtil.init(reader.readLines());
        logger.info("initialize bean:{}", SensitiveWordConfig.class.getName());
    }

	/**
	 * 敏感词过滤替换 ***
	 */
    public static String sensitiveWordFiltering(String text) {
        List<FoundWord> matchAll = SensitiveUtil.getFoundAllSensitive(text, false, false);
        if (matchAll.size() > 0) {
            for (FoundWord match : matchAll) {
                text = StrUtil.replace(text, match.getStartIndex(), match.getEndIndex() + 1, '*');
            }
        }
        return text;
    }
}

